1. Implicit Route Model Binding
// Define a route with implicit model binding
Route::get('user/{user}', [UserController::class, 'show'])->name('user.show');
// In UserController
public function show(User $user)
{
return view('user.show', compact('user'));
}
Route::get('user/{user}', [UserController::class, 'show']) automatically resolves the User model for the {user} parameter using its primary key.Route Definition:
Laravel injects the User model instance directly into the show method, simplifying code and avoiding manual query logic.Controller Method:
2. Explicit Route Model Binding
// Define a route with explicit model binding
Route::get('post/{post}', [PostController::class, 'show'])->name('post.show');
// In AppServiceProvider
public function boot()
{
parent::boot();
Route::bind('post', function ($value) {
return Post::where('slug', $value)->firstOrFail();
});
}
// In PostController
public function show(Post $post)
{
return view('post.show', compact('post'));
}
Route::get('post/{post}', [PostController::class, 'show']) uses explicit binding to handle custom retrieval logic.Route Definition:
In AppServiceProvider, Route::bind('post', function ($value) { ... }) allows you to define how the model should be resolved, such as using a non-primary key (e.g., slug).Custom Binding Logic:
Laravel injects the Post model instance, resolved by the custom logic, into the show method.Controller Method:
Difference
Automatically resolves models based on route parameters and primary keys, making code cleaner and easier to maintain.Implicit Binding:
Allows custom logic for model retrieval, offering more flexibility in how models are resolved.Explicit Binding:
You Might Also Like
Apply Select Statements for Efficient Data Retrieval
Retrieve only the necessary columns from the database to reduce memory usage and speed up queries. T...
Optimize Queries with Eager Loading
Reduce the number of database queries by using Eager Loading. Eager Loading helps you load related m...